package com.platform.module.common.utils;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import java.util.Set;

@Slf4j
public class ValidatorUtils {
    public static ValidatorUtils INSTANCE = new ValidatorUtils();

    private static Validator VALIDATOR = Late.proxy(Validator.class, () -> Validation.buildDefaultValidatorFactory().getValidator());

    /***
     * 断言bean格式正确
     * @param object 要验证的对象
     */
    public void assertValid(Object object) {
        Validator validator = null;
        try {
            ApplicationContext context = SpringUtils.getContext();
            if (context == null) {
                log.warn("无法获得spring容器,可能是spring未初始化完成");
                validator = ValidatorUtils.VALIDATOR;
            } else {
                validator = context.getBean(Validator.class);
            }
        } catch (Exception e) {
            log.warn("无法从spring中获取到验证器:{}", e.getMessage(), e);
            validator = ValidatorUtils.VALIDATOR;
        }
        Set<ConstraintViolation<Object>> errors = validator.validate(object);
        if (!errors.isEmpty()) {
            throw new ConstraintViolationException(errors);
        }
    }
}
